package com.example.programme;

import static android.content.ContentValues.TAG;


import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.programme.Items.UserItem;
import com.example.programme.database.UserDBHelper;
import com.example.programme.database.UserManager;

public class RegisterActivity extends AppCompatActivity{
    EditText et_name2,et_password2;
    Button  button3;
    UserDBHelper userDBHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
//

        button3 = findViewById(R.id.button2);
        et_name2 = findViewById(R.id.et_name2);
        et_password2=findViewById(R.id.et_password2);

        userDBHelper = new UserDBHelper(RegisterActivity.this);
    }

    public void button3(View btn){
        String name = et_name2.getText().toString().trim();
        String password = et_password2.getText().toString().trim();

        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(password)) {
            //连接数据库
            boolean flag1=false;
            SQLiteDatabase db=userDBHelper.getReadableDatabase();
            UserManager userManager=new UserManager(RegisterActivity.this);
            // TODO 补充不能重复注册同一账号的代码
            if (userManager.listAll() != null) {//调用方法获取数据库中的单词
                for (UserItem user : userManager.listAll()) {

                    if (user.getName().equals(name)) {
                        flag1 = true;//有重复的数据
                    }
                }
                if (flag1 == false) {
                    //加入值
                    userManager.add(name, password);
                    MyToast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT);
                } else MyToast.makeText(RegisterActivity.this, "您已注册", Toast.LENGTH_SHORT);
            }else {
                userManager.add(name, password);
                MyToast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT);
            }
 //------返回登录页面 --------

            Log.i(TAG, "click: 成功封装");
            Intent  intent =getIntent();
            Bundle  bdl =new Bundle();
            bdl.putString("name_key",name);
            bdl.putString("password_key",password);
            intent.putExtras(bdl);
            setResult(2,intent);//响应代码

            finish();
            Log.i(TAG, "click: 成功返回");

        }else {MyToast.makeText(RegisterActivity.this,"请正确输入信息",Toast.LENGTH_LONG);
        }

    }
}